package com.example.neutonote2.api;

import android.util.Log;

import com.example.neutonote2.data.model.Note;
import com.example.neutonote2.data.model.NoteWithTags;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * DeepSeek API客户端
 */
public class DeepseekApiClient {
    private static final String TAG = "DeepseekApiClient";
    // API端点，针对不同功能
    private static final String API_ENDPOINT_CHAT = "https://api.deepseek.com/chat/completions";
    private static final String API_ENDPOINT_BETA = "https://api.deepseek.com/beta/completions";
    private static DeepseekApiClient instance;
    private final String apiKey;
    private final OkHttpClient client;
    
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    private DeepseekApiClient(String apiKey) {
        this.apiKey = apiKey;
        this.client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)  // 进一步缩短连接超时
                .writeTimeout(30, TimeUnit.SECONDS)    // 缩短写入超时
                .readTimeout(30, TimeUnit.SECONDS)     // 缩短读取超时
                .retryOnConnectionFailure(true)        // 启用连接失败重试
                .build();
    }

    public static synchronized DeepseekApiClient getInstance(String apiKey) {
        if (instance == null || !instance.apiKey.equals(apiKey)) {
            instance = new DeepseekApiClient(apiKey);
        }
        return instance;
    }

    /**
     * 发送笔记内容到DeepSeek API进行处理
     * @param note 要处理的笔记
     * @param prompt 提示词
     * @param useChat 是否使用chat API (true: chat/completions, false: beta/completions)
     * @return 处理结果
     */
    public String processNote(NoteWithTags note, String prompt, boolean useChat) {
        Response response = null;
        try {
            if (note == null || note.note == null) {
                Log.e(TAG, "笔记对象为空");
                return "笔记内容不能为空";
            }
            
            String content = note.note.getContent();
            if (content == null) {
                content = "";
            }
            
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("model", "deepseek-chat");
            
            String apiEndpoint;
            
            if (useChat) {
                // 构建 chat/completions API 所需的消息数组
                JSONArray messages = new JSONArray();
                
                // 添加系统消息
                JSONObject systemMessage = new JSONObject();
                systemMessage.put("role", "system");
                systemMessage.put("content", "你是一个智能笔记助手，可以帮助用户处理笔记内容。");
                messages.put(systemMessage);
                
                // 添加用户消息
                JSONObject userMessage = new JSONObject();
                userMessage.put("role", "user");
                userMessage.put("content", prompt + "\n\n笔记内容：\n" + content);
                messages.put(userMessage);
                
                // 将消息数组添加到请求体
                jsonBody.put("messages", messages);
                apiEndpoint = API_ENDPOINT_CHAT;
            } else {
                // 使用FIM格式用于beta/completions
                jsonBody.put("prompt", "你是一个智能笔记助手，可以帮助用户处理笔记内容。\n\n" + prompt + "\n\n笔记内容：\n" + content);
                apiEndpoint = API_ENDPOINT_BETA;
            }
            
            jsonBody.put("temperature", 0.7);
            jsonBody.put("max_tokens", 1000);

            String jsonRequest = jsonBody.toString();
            Log.d(TAG, "API请求内容: " + jsonRequest);
            
            RequestBody body = RequestBody.create(jsonRequest, JSON);
            Request request = new Request.Builder()
                    .url(apiEndpoint)
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .addHeader("Content-Type", "application/json")
                    .post(body)
                    .build();

            Log.d(TAG, "发送API请求: " + apiEndpoint);
            // 安全记录请求信息，不包含敏感内容
            Log.d(TAG, "请求头: Content-Type=application/json, Authorization=Bearer ******");
            
            try {
                response = client.newCall(request).execute();
                Log.d(TAG, "API响应状态码: " + response.code());
                if (!response.isSuccessful()) {
                    Log.e(TAG, "API调用失败: " + response.code() + " " + response.message());
                    String errorBody = response.body() != null ? response.body().string() : "无响应体";
                    Log.e(TAG, "错误响应: " + errorBody);
                    
                    // 尝试解析错误信息
                    try {
                        JSONObject errorJson = new JSONObject(errorBody);
                        if (errorJson.has("error")) {
                            JSONObject error = errorJson.getJSONObject("error");
                            String errorMessage = error.optString("message", "未知错误");
                            return "API调用失败: " + errorMessage;
                        }
                    } catch (JSONException je) {
                        Log.e(TAG, "解析错误响应失败", je);
                    }
                    
                    if (response.code() == 401) {
                        return "API密钥认证失败，请检查API密钥是否正确";
                    } else if (response.code() == 403) {
                        return "API密钥权限不足或已过期";
                    } else if (response.code() == 429) {
                        return "API请求过于频繁，请稍后再试";
                    } else if (response.code() >= 500) {
                        return "DeepSeek服务器错误，请稍后再试";
                    }
                    
                    return "API调用失败，错误码: " + response.code() + "，" + errorBody;
                }
                
                String responseBody = response.body() != null ? response.body().string() : "";
                if (responseBody.isEmpty()) {
                    Log.e(TAG, "API响应为空");
                    return "API响应为空";
                }
                
                Log.d(TAG, "API响应: " + responseBody);
                
                try {
                    JSONObject jsonResponse = new JSONObject(responseBody);
                    
                    if (useChat) {
                        // 解析 chat/completions API 响应格式
                        if (jsonResponse.has("choices") && jsonResponse.getJSONArray("choices").length() > 0) {
                            JSONArray choices = jsonResponse.getJSONArray("choices");
                            JSONObject choice = choices.getJSONObject(0);
                            
                            if (choice.has("message")) {
                                JSONObject message = choice.getJSONObject("message");
                                if (message.has("content")) {
                                    return message.getString("content");
                                }
                            }
                        }
                    } else {
                        // 解析beta/completions响应
                        if (jsonResponse.has("completion")) {
                            return jsonResponse.getString("completion");
                        } else if (jsonResponse.has("choices") && jsonResponse.getJSONArray("choices").length() > 0) {
                            JSONArray choices = jsonResponse.getJSONArray("choices");
                            JSONObject choice = choices.getJSONObject(0);
                            
                            if (choice.has("text")) {
                                return choice.getString("text");
                            }
                        }
                    }
                    
                    Log.e(TAG, "响应格式不正确");
                    return "API响应格式错误: 无法解析";
                } catch (JSONException e) {
                    Log.e(TAG, "解析API响应JSON失败", e);
                    return "解析API响应失败: " + e.getMessage() + "\n\n原始响应: " + responseBody;
                }
            } catch (IOException e) {
                Log.e(TAG, "网络错误: " + e.getMessage(), e);
                return "处理失败，网络错误: " + e.getMessage();
            } catch (Exception e) {
                Log.e(TAG, "其他错误: " + e.getMessage(), e);
                return "处理失败，错误: " + e.getMessage();
            }
        } catch (JSONException e) {
            Log.e(TAG, "构建请求JSON失败: " + e.getMessage(), e);
            return "处理失败，JSON错误: " + e.getMessage();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    Log.e(TAG, "关闭响应异常: " + e.getMessage(), e);
                }
            }
        }
    }
    
    /**
     * 生成笔记摘要
     * @param content 笔记内容
     * @return 生成的摘要
     */
    public String summarizeNote(String content) {
        Response response = null;
        try {
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("model", "deepseek-chat");
            
            // 构建 chat/completions API 所需的消息数组
            JSONArray messages = new JSONArray();
            
            // 添加系统消息
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", "system");
            systemMessage.put("content", "你是一个专业的笔记摘要工具，擅长提取文本中的重要信息并生成简明扼要的摘要。");
            messages.put(systemMessage);
            
            // 添加用户消息
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", "请为以下笔记内容生成一个简洁的摘要（不超过200字）：\n\n" + content);
            messages.put(userMessage);
            
            // 将消息数组添加到请求体
            jsonBody.put("messages", messages);
            jsonBody.put("temperature", 0.3);
            jsonBody.put("max_tokens", 500);

            String jsonRequest = jsonBody.toString();
            Log.d(TAG, "摘要生成请求内容: " + jsonRequest);
            
            RequestBody body = RequestBody.create(jsonRequest, JSON);
            Request request = new Request.Builder()
                    .url(API_ENDPOINT_CHAT)
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .addHeader("Content-Type", "application/json")
                    .post(body)
                    .build();

            Log.d(TAG, "发送摘要生成请求");
            // 安全记录请求信息，不包含敏感内容
            Log.d(TAG, "请求头: Content-Type=application/json, Authorization=Bearer ******");
            
            try {
                response = client.newCall(request).execute();
                Log.d(TAG, "摘要生成响应状态码: " + response.code());
                if (!response.isSuccessful()) {
                    Log.e(TAG, "摘要生成失败: " + response.code() + " " + response.message());
                    String errorBody = response.body() != null ? response.body().string() : "无响应体";
                    Log.e(TAG, "错误响应: " + errorBody);
                    
                    if (response.code() == 401) {
                        return "API密钥认证失败";
                    } else if (response.code() == 403) {
                        return "API密钥权限不足";
                    } else if (response.code() == 429) {
                        return "API请求过于频繁";
                    } else if (response.code() >= 500) {
                        return "API服务器错误";
                    }
                    
                    return "生成失败，错误码: " + response.code();
                }
                
                String responseBody = response.body() != null ? response.body().string() : "";
                
                Log.d(TAG, "摘要生成响应: " + responseBody);
                
                try {
                    JSONObject jsonResponse = new JSONObject(responseBody);
                    
                    // 解析响应
                    JSONArray choices = jsonResponse.getJSONArray("choices");
                    JSONObject choice = choices.getJSONObject(0);
                    JSONObject message = choice.getJSONObject("message");
                    return message.getString("content");
                } catch (JSONException e) {
                    Log.e(TAG, "解析摘要生成响应失败: " + e.getMessage(), e);
                    return "解析响应失败: " + e.getMessage();
                }
            } catch (Exception e) {
                Log.e(TAG, "摘要生成网络错误: " + e.getMessage(), e);
                return "生成失败，网络错误: " + e.getMessage();
            }
        } catch (JSONException e) {
            Log.e(TAG, "构建摘要生成请求失败: " + e.getMessage(), e);
            return "构建请求失败: " + e.getMessage();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    Log.e(TAG, "关闭摘要生成响应异常: " + e.getMessage(), e);
                }
            }
        }
    }
} 